package cn.xorange.commons.security.utils;

import cn.xorange.commons.security.entity.ClaimsInfo;
import cn.xorange.commons.utils.cache.ICacheService;
import cn.xorange.commons.utils.lang.ObjectUtils;
import cn.xorange.commons.utils.spring.SpringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.Objects;


/**
 * @author : yangjian
 * date : 2023/11/26
 * description :
 */
public class SecurityUtils {
    SecurityUtils(){}

    private static Authentication getAuthentication(){
        return SecurityContextHolder.getContext().getAuthentication();
    }

    public static ClaimsInfo getClaimsInfo(){
        Object object = getAuthentication().getDetails();
        if(object instanceof ClaimsInfo){
            return (ClaimsInfo)object;
        }else {
            return null;
        }
    }

    public static String getTokenKey(){
        return ObjectUtils.toString(getAuthentication().getCredentials());
    }

    public static <T> T getUser(){
        String tokenKey = SecurityUtils.getTokenKey();
        return SpringUtils.getBean(ICacheService.class).getCacheObject(tokenKey);
    }

    public static Long getUserId(){
        return ObjectUtils.toLong(getAuthentication().getPrincipal());
    }

    public static Long getTenantId(){
        ClaimsInfo claimsInfo = getClaimsInfo();
        if(Objects.isNull(claimsInfo)){
            return null;
        }else {
            return claimsInfo.getTenantId();
        }
    }

    public static String getUsername(){
        ClaimsInfo claimsInfo = getClaimsInfo();
        if(Objects.isNull(claimsInfo)){
            return null;
        }else {
            return claimsInfo.getUsername();
        }
    }

    public static boolean userIsAdmin(){
        ClaimsInfo claimsInfo = getClaimsInfo();
        if(Objects.isNull(claimsInfo)){
            return false;
        }else {
            return claimsInfo.isAdmin();
        }
    }


    /**
     * 生成BCryptPasswordEncoder密码
     *
     * @param password 密码
     * @return 加密字符串
     *
     * @since 2.2.1 modify by aes加密
     */
    public static String encryptPassword(String password) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode(password);
    }

    /**
     * 判断密码是否相同
     *
     * @param realPassword 真实密码
     * @param encodedPassword 加密后字符
     * @return 结果
     *
     * @since 2.2.1 modify by aes加密
     */
    public static boolean matchesPassword(String realPassword, String encodedPassword) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.matches(realPassword, encodedPassword);
    }

}
